<?php

class M_weixin extends CI_Model {

    private $app_id;
    private $app_secret;

    public function __construct() {
        parent::__construct();
        $wechat_config = $this->db->select('*')->get_where('weixinconfig')->row_array();
        $this->app_id = $wechat_config['appid'];
        $this->app_secret = $wechat_config['appsecret'];
    }

    /*获取access_token*/
    public function get_access_token(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->app_id."&secret=".$this->app_secret;
        $response = file_get_contents($url);
        $response = json_decode($response,true);
        return $response;
    }

    /*格式化传进来的参数，拼接成请求的url*/
    private function format_url($intertype){

        $str = implode('/',$intertype);
        $access_token = $this->session->userdata('access_token');
        if(empty($access_token)){
            $response = $this->get_access_token();
            if(isset($response['errcode'])){
                return $response;
            }else{
                $access_token = $response['access_token'];
                $token_data = array('access_token'=>$access_token);
                $this->session->set_userdata($token_data);
            }
        }

        $url = "https://api.weixin.qq.com/cgi-bin/";

        $url .= $str.'?access_token='.$access_token;

        return $url;
    }

    public function synoc_weixin($data_string,$intertype){
        $url = $this->format_url($intertype);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($return_code != 200){
            return false;
        }
        return json_decode($return_content,true);
    }

    public function synoc_weixin_xml($data_string,$intertype){
        $url = $this->format_url($intertype);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/xml; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($return_code != 200){
            return false;
        }
        return json_decode($return_content,true);
    }

}
